package cn.iocoder.yudao.framework.apijson.config;

import apijson.Log;
import apijson.StringUtil;
import apijson.framework.APIJSONApplication;
import apijson.framework.APIJSONConstant;
import apijson.framework.APIJSONCreator;
import apijson.orm.*;
import cn.iocoder.yudao.framework.apijson.core.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;

import java.util.Map;
import java.util.regex.Pattern;

@AutoConfiguration
@Slf4j
public class ApiJsonAutoConfiguration {

    @EventListener(ApplicationReadyEvent.class)
    public void onApplicationReady(ApplicationReadyEvent application) {
        try {
            log.info("初始化ApiJson");
            unitauto.Log.DEBUG = Log.DEBUG = false;
            APIJSONApplication.init();
            log.info("初始化ApiJson成功");
        } catch (Exception e) {
            log.error("初始化ApiJson失败", e);
            throw new RuntimeException(e);
        }
    }

    static {
        Map<String, Pattern> COMPILE_MAP = AbstractVerifier.COMPILE_MAP;
        COMPILE_MAP.put("PHONE", StringUtil.PATTERN_PHONE);
        COMPILE_MAP.put("EMAIL", StringUtil.PATTERN_EMAIL);
        COMPILE_MAP.put("ID_CARD", StringUtil.PATTERN_ID_CARD);
        // 使用本项目的自定义处理类
        APIJSONApplication.DEFAULT_APIJSON_CREATOR = new APIJSONCreator<Long>() {

            @Override
            public Parser<Long> createParser() {
                return new ApiJsonParser();
            }

            @Override
            public FunctionParser createFunctionParser() {
                return new ApiJsonFunctionParser();
            }

            @Override
            public Verifier<Long> createVerifier() {
                return new ApiJsonVerifier();
            }

            @Override
            public SQLConfig createSQLConfig() {
                return new ApiJsonSQLConfig();
            }

            @Override
            public SQLExecutor createSQLExecutor() {
                return new ApiJsonSQLExecutor();
            }

        };
    }


}
